package com.wfy.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wfy.mapper.BrandMapper;
import com.wfy.pojo.Brand;
import com.wfy.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Title: BrandService
 * @Package com.wfy.service
 * @Author 王飞遥
 * @Date 2022/8/17 20:31
 */
@Service
public class BrandService {
    @Autowired
    BrandMapper brandMapper;
    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //先初始化查询的对象条件
        Example example = new Example(Brand.class);
        //进行实例化 构造器
        Example.Criteria criteria = example.createCriteria();
        //根据某个条件 做模糊查询 或者根据首字母查询
        //如果不为空 sql继续构造 不负责排序
        if(!StringUtils.isEmpty(key)){
            //根据名称查询或者根据名称首字母查询
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        //添加分页条件
        PageHelper.startPage(page,rows);
        //添加排序的条件
        if(!StringUtils.isEmpty(sortBy)){
            //如果sortBy不为空 进行排序
            //order by id desc
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }
        //执行查询
        List<Brand> brands = brandMapper.selectByExample(example);
        //包装数据返回PageResult对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        //这里要注意，因为我们不仅要新增品牌还要维护品牌和商品分类的中间表

        //新增brand
        brandMapper.insertSelective(brand);


        //新增中间表  jdk1.8的新特性 Lomd表达式
        // cid 起的每一个对象的别名
        cids.forEach(cid ->{
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        });
    }

    public List<Brand> queryBrandByCid(Long cid) {
        return brandMapper.queryBrandByCid(cid);
    }

    public Brand queryBrandInfoById(Long brandId) {
        return brandMapper.selectByPrimaryKey(brandId);
    }
}
